package com.library.web.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*") // 拦截所有请求
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 转换为Http相关对象（便于操作会话和请求路径）
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        // 登录相关路径、静态资源（CSS/JS/图片）放行
        if (requestURI.startsWith(contextPath + "/login")  // 登录页及登录提交接口
                || requestURI.startsWith(contextPath + "/css/")  // CSS样式
                || requestURI.startsWith(contextPath + "/js/")   // JS脚本
                || requestURI.startsWith(contextPath + "/images/")  // 图片资源
                || requestURI.equals(contextPath + "/")  // 网站首页
                || requestURI.endsWith(".ico")) {  // 网站图标
            // 公开资源直接放行
            filterChain.doFilter(request, response);
            return;
        }
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        if (user != null) {
            filterChain.doFilter(request, response);
        } else {
            response.sendRedirect(contextPath + "/login");
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化时执行（可留空）
    }

    @Override
    public void destroy() {
        // 过滤器销毁时执行（可留空）
    }
}
